package org.luxor.commons.rabbitmq.service.workqueue;

import com.rabbitmq.client.Channel;
import org.luxor.commons.core.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Argument;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 二号消费者
 *
 * @author Mr.Yan  @date 2019/10/16$
 */
@Component
public class TwoConsumer {
    private static final Logger log = LoggerFactory.getLogger(TwoConsumer.class);

    @RabbitListener(queuesToDeclare = @Queue(name = "queue.work", arguments = {
            @Argument(name = "x-dead-letter-exchange", value = "dead.exchange"),// 指定死信交换器
            @Argument(name = "x-max-priority", value = "5")// 设置队列最大优先级
    }))
    public void onMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        log.info("2 号消费者, 接收到任务：" + message);

        try {
            handle(message);
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (BaseException e) {
            log.warn("<<< 2 号消费者处理任务失败 channel:[{}]", channel);
            // 拒绝消息，并重新返回到队列中
            channel.basicReject(deliveryTag, true);
            // 拒绝消息，并直接删除这条记录
            //channel.basicReject(deliveryTag, false);
        }
    }

    /**
     * 处理一条接收到的消息
     */
    private void handle(String message) throws BaseException {
        log.info("2 号消费者，执行任务【成功】");
    }
}
